package com.qh.paythird.wxpay.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by  梦想达到
 * 描述httpclient工具类
 */
public class HttpClientUtil {
    private final static Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);

    private final static int defaultHttpTimeout = 6000;

    public static String doGet(String url, Map<String, String> param) {
        return doGet(url, param, defaultHttpTimeout);
    }

    public static String doGet(String url, Map<String, String> param, int timeout) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        HttpGet httpGet = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            httpGet = new HttpGet(uri);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();//设置请求和传输超时时间
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            abortHttpBase(httpGet);
            LOGGER.error("doGet出错:{}", e);
        } finally {
            closeHttpClient(httpclient, response);
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null, defaultHttpTimeout);
    }

    public static String doPost(String url, Map<String, String> param) {
        return doPost(url, param, defaultHttpTimeout);
    }

    public static String doPost(String url, Map<String, String> param, int timeout) {
        return doPost(url, param, null, null, timeout);
    }

    public static String doPost(String url, Map<String, String> param, Map<String, String> headers) {
        return doPost(url, param, headers, null, defaultHttpTimeout);
    }

    public static String doPost(String url, Map<String, String> param, Map<String, String> headers, String payloadStr, int timeout) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        HttpPost httpPost = null;
        try {
            // 创建Http Post请求
            httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity(entity);
            }
            // 创建header
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.setHeader(key, headers.get(key));
                }
            }
            // 创建字符串样式payload
            if (payloadStr != null) {
                StringEntity stringEntity = new StringEntity(payloadStr, "application/json", "utf-8");
                httpPost.setEntity(stringEntity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            httpPost.abort();
            LOGGER.error("doPost出错:{}", e);
        } finally {
            closeHttpClient(httpClient, response);
        }
        return resultString;
    }


    public static String doPost(String url) {
        return doPost(url, null, defaultHttpTimeout);
    }

    public static String doPostJson(String url, String json){
        return doPostJson(url, json, defaultHttpTimeout);
    }

    public static String doPostJson(String url, String json, int timeout) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        HttpPost httpPost = null;
        try {
            // 创建Http Post请求
            httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            abortHttpBase(httpPost);
            LOGGER.error("doPostJSON出错:{}", e);
        } finally {
            closeHttpClient(httpClient, response);
        }

        return resultString;
    }

    public static String doPostXMl(String url, String xml) {
        return doPostXMl(url, xml, defaultHttpTimeout);
    }

    public static String doPostXMl(String url, String xml, int timeout) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        HttpPost httpPost = null;
        try {
            // 创建Http Post请求
            httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            // 创建请求内容
            StringEntity entity = new StringEntity(xml);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            abortHttpBase(httpPost);
            LOGGER.error("doPostxml出错:{}", e);
        } finally {
            closeHttpClient(httpClient, response);
        }
        return resultString;
    }

    public static String postHttpsData(String url, String xmlObj, String password, String certPath) {
        return postHttpsData(url, xmlObj, password, certPath, defaultHttpTimeout);
    }


    /**
     * http post,有返回String
     *
     * @param requrl
     * @param req
     * @param connTimeOut
     * @param readTimeOut
     * @return
     */
    public static String postReq(String requrl, String req, int connTimeOut, int readTimeOut) {
        HttpURLConnection conn = null;
        OutputStreamWriter out = null;
        BufferedReader in = null;
        InputStreamReader is = null;
        try {
            try {
                URL url = new URL(requrl);
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(true);    //POST
                conn.setRequestMethod("POST");
                conn.setUseCaches(false);
                conn.setConnectTimeout(connTimeOut);
                conn.setReadTimeout(readTimeOut);
                conn.connect();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out.write(req);
            out.flush();
            out.close();

            is = new InputStreamReader(conn.getInputStream(), "utf-8");
            in = new BufferedReader(is);
            StringBuilder sb = new StringBuilder();
            char[] buff = new char[2048];
            int cnt = 0;
            while ((cnt = in.read(buff)) != -1)
                sb.append(buff, 0, cnt);
            in.close();
            String rtStr = sb.toString();
            return rtStr;
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
            throw new RuntimeException(e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    LOGGER.error("", e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    LOGGER.error("", e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    LOGGER.error("", e);
                }
            }
            if (conn != null)
                conn.disconnect();
        }
    }


    /**
     * https post请求
     *
     * @param url      请求地址
     * @param xmlObj   请求内容
     * @param password 证书密码
     * @param certPath 证书路径
     * @param timeout  超时时间
     * @return
     */
    public static String postHttpsData(String url, String xmlObj, String password, String certPath, int timeout) {
        CloseableHttpClient httpClient = null;
        // 加载证书
        try {
            httpClient = initCert(password, certPath);
        } catch (Exception e) {
            LOGGER.error("微信退款证书读取失败", e);
        }
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        // 得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
        StringEntity postEntity = new StringEntity(xmlObj, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(postEntity);
        // 根据默认超时限制初始化requestConfig
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(timeout)
                .setConnectTimeout(timeout)
                .build();
        // 设置请求器的配置
        httpPost.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        try {
            try {
                response = httpClient.execute(httpPost);
            } catch (IOException e) {
                LOGGER.error("", e);
            }
            HttpEntity entity = response.getEntity();
            try {
                result = EntityUtils.toString(entity, "UTF-8");
            } catch (IOException e) {
                LOGGER.error("", e);
            }
        } catch (Exception e) {
            abortHttpBase(httpPost);
            LOGGER.error("timeoutdoPostJSON出错:{}", e);
        } finally {
            closeHttpClient(httpClient, response);
        }
        return result;
    }

    /**
     * 加载证书
     */
    private static CloseableHttpClient initCert(String password, String certPath) throws Exception {
        // 指定读取证书格式为PKCS12
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        // 读取本机存放的PKCS12证书文件
        FileInputStream instream = new FileInputStream(new File(certPath));
        try {
            // 指定PKCS12的密码(商户ID)
            keyStore.load(instream, password.toCharArray());
        } finally {
            instream.close();
        }
        SSLContext sslcontext = SSLContexts
                .custom()
                .loadKeyMaterial(keyStore, password.toCharArray())
                .build();
        // 指定TLS版本
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext, new String[]{"TLSv1"}, null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        // 设置httpclient的SSLSocketFactory
        CloseableHttpClient httpClient = HttpClients
                .custom()
                .setSSLSocketFactory(sslsf)
                .build();
        return httpClient;
    }


    private static void closeHttpClient(CloseableHttpClient httpClient, CloseableHttpResponse response) {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                LOGGER.error("关response出错:{}", e);
            }
        }
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (Exception e1) {
                LOGGER.error("关client出错:{}", e1);
            }
        }
    }

    private static void abortHttpBase(HttpRequestBase base) {
        if (base != null) {
            base.abort();
        }
    }
}
